package top.huxy.boot.config.messageConverter;

import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.server.ServletServerHttpResponse;
import top.huxy.boot.util.obj.Result;
import top.huxy.boot.util.obj.ThreadLocalRequestStartTime;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @Classname ResultMessageConverter
 * @Description ResultMessageConverter
 * @Date 2021/8/30 19:14
 * @Created by huxy
 */
public class ResultMessageConverter extends AbstractHttpMessageConverter<Result> {

    public ResultMessageConverter() {
        super(MediaType.ALL, MediaType.APPLICATION_JSON);
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return clazz == Result.class;
    }

    @Override
    protected Result readInternal(Class<? extends Result> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    @Override
    protected void writeInternal(Result result, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        long start = ThreadLocalRequestStartTime.get();
        long now = System.currentTimeMillis();
        result.setProcessingTime(now - start);
        if(outputMessage instanceof ServletServerHttpResponse){
            HttpServletResponse response = ((ServletServerHttpResponse) outputMessage).getServletResponse();
            HashMap<String, Object> remarks = result.getRemarks();
            String rmk;
            if(remarks!=null){
                rmk=JSON.toJSONString(remarks);
                response.setHeader("remakes",rmk);
            }
        }
        outputMessage.getBody().write(JSON.toJSONBytes(result));
    }
}
